import React, { useState, useEffect } from 'react';
import Web3 from 'web3';

// 导入智能合约ABI
const contractABI = [{ "inputs": [ { "internalType": "string", "name": "initMessage", "type": "string" } ], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [], "name": "message", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "string", "name": "newMessage", "type": "string" } ], "name": "updateMessage", "outputs": [], "stateMutability": "nonpayable", "type": "function" }];

const ContractAddress = '0x31566Ec23b40C7E68D9a8650446C1271931dA499'; // 存储智能合约地址

function App() {
  const [web3, setWeb3] = useState(null);
  const [contractInstance, setContractInstance] = useState(null);
  const [accounts, setAccounts] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [message, setMessage] = useState('');

  useEffect(() => {
    async function init() {
      if (window.ethereum) {
        try {
          await window.ethereum.enable();
          const web3 = new Web3(window.ethereum);
          const contract = new web3.eth.Contract(contractABI, ContractAddress);
          const accounts = await web3.eth.getAccounts();
          const message = await contract.methods.message().call();
          setMessage(message);
          setWeb3(web3);
          setContractInstance(contract);
          setAccounts(accounts);
          
        } catch (error) {
          console.error(error);
        }
      } else {
        console.log('Please install MetaMask!');
      }
    }
    init();
  }, []);

  async function handleClick() {
    try {
      const result = await contractInstance.methods.updateMessage(inputValue).send({
        from: accounts[0],
      });
      console.log(result); // 处理交易结果
      const message = await contractInstance.methods.message().call();
      setMessage(message);
    } catch (error) {
      console.error(error);
    }
  }

  return (
    <div>
      <h1>调用智能合约并使用MetaMask签名</h1>
      {web3 && contractInstance && accounts.length > 0 ? (
        <>
          <p>当前消息内容：{message}</p>
          <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} />
          <button onClick={handleClick}>调用智能合约</button>
        </>
      ) : (
        <p>正在加载...</p>
      )}
    </div>
  );
}

export default App;